package com.flowable.controller;

import org.flowable.engine.HistoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.history.HistoricProcessInstanceQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/statistics")
public class ProcessStatisticsController {

    @Autowired
    private RuntimeService runtimeService;
    
    @Autowired
    private HistoryService historyService;

    /**
     * 获取流程统计数据
     */
    @GetMapping
    public Map<String, Object> getProcessStatistics() {
        Map<String, Object> stats = new HashMap<>();
        
        // 1. 运行中的流程数量
        long runningCount = runtimeService.createProcessInstanceQuery()
                .active() // 只统计活跃的流程实例
                .count();
        
        // 2. 已完成的流程数量
        long completedCount = historyService.createHistoricProcessInstanceQuery()
                .finished() // 只统计已完成的流程实例
                .count();


        HistoricProcessInstanceQuery finished = historyService.createHistoricProcessInstanceQuery().finished();
        System.err.println(finished);

        // 3. 平均处理时间（小时）
        double avgTime = calculateAverageProcessTime();
        
        // 4. 审批通过率（假设通过特定的结束原因判断）
        long approvedCount = historyService.createHistoricProcessInstanceQuery()
                .finished()
                .variableValueEquals("approvalResult", "approved") // 假设流程变量中存储了审批结果
                .count();
        
        int approvalRate = completedCount > 0 ? (int) (approvedCount * 100 / completedCount) : 0;
        
        // 5. 最近7天的流程趋势数据
        Map<String, List<Integer>> trendData = getLast7DaysTrend();
        
        // 组装返回结果
        stats.put("running", runningCount);
        stats.put("completed", completedCount);
        stats.put("avgTime", Math.round(avgTime * 10) / 10.0); // 保留一位小数
        stats.put("approvalRate", approvalRate);
        stats.put("trendLabels", trendData.get("labels"));
        stats.put("trendData", trendData.get("data"));
        
        return stats;
    }
    
    /**
     * 计算平均流程处理时间（小时）
     */
    private double calculateAverageProcessTime() {
        // 只统计最近30天内完成的流程，避免数据量过大
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -30);
        Date thirtyDaysAgo = calendar.getTime();

        List<HistoricProcessInstance> completedProcesses = historyService.createHistoricProcessInstanceQuery()
                .finished() // 筛选已结束的流程
                .finishedAfter(thirtyDaysAgo) // 筛选在thirtyDaysAgo之后结束的流程
                .listPage(0, 1000); // 限制最多统计1000条记录
        
        if (completedProcesses.isEmpty()) {
            return 0;
        }
        
        long totalDurationMillis = 0;
        for (HistoricProcessInstance process : completedProcesses) {
            if (process.getEndTime() != null && process.getStartTime() != null) {
                totalDurationMillis += process.getEndTime().getTime() - process.getStartTime().getTime();
            }
        }
        
        // 转换为小时
        return (totalDurationMillis / (1000.0 * 60 * 60)) / completedProcesses.size();
    }
    
    /**
     * 获取最近7天的流程趋势数据
     */
    private Map<String, List<Integer>> getLast7DaysTrend() {
        Map<String, List<Integer>> result = new HashMap<>();
        List<Integer> data = new java.util.ArrayList<>();
        List<Integer> labels = new java.util.ArrayList<>();
        
        Calendar calendar = Calendar.getInstance();
        
        // 收集最近7天的数据
        for (int i = 6; i >= 0; i--) {
            calendar.add(Calendar.DAY_OF_MONTH, i == 6 ? -6 : -1); // 从6天前开始
            
            Date startOfDay = getStartOfDay(calendar.getTime());
            Date endOfDay = getEndOfDay(calendar.getTime());
            
            // 统计当天启动的流程数量
            long count = historyService.createHistoricProcessInstanceQuery()
                    .startedAfter(startOfDay)
                    .startedBefore(endOfDay)
                    .count();
            
            data.add((int) count);
            // 存储月份和日期的数字表示（如8月4日存储为804）
            labels.add(calendar.get(Calendar.MONTH) + 1 * 100 + calendar.get(Calendar.DAY_OF_MONTH));
            
            if (i < 6) {
                calendar.add(Calendar.DAY_OF_MONTH, 1); // 重置日期用于下一次计算
            }
        }
        
        result.put("data", data);
        result.put("labels", labels);
        return result;
    }
    
    /**
     * 获取一天的开始时间（00:00:00）
     */
    private Date getStartOfDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();
    }
    
    /**
     * 获取一天的结束时间（23:59:59）
     */
    private Date getEndOfDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTime();
    }
}
